package com.yulebaby.callsenter.ui.base;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.event.RefreshEvent;
import com.yulebaby.callsenter.event.TabSelectedEvent;
import com.yulebaby.callsenter.http.callback.HttpCallback;
import com.yulebaby.callsenter.ui.view.StateViewLayout;
import com.yulebaby.callsenter.ui.view.YuLeBaByLinearLayoutManager;
import com.yulebaby.callsenter.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * 封装自带RecycleView 下拉刷新的Fragment 及访问回调处理的Fragment  有生命周期和懒加载的优化
 * Author: Zhangbo
 *
 * @param <T> Bean对象
 * @param <K> Adapter
 */

public abstract class BaseRecycleViewFragment<T, K extends RecyclerView.Adapter> extends BaseFragment implements OnRefreshListener, EasyPermissions.PermissionCallbacks, StateViewLayout.OnReloadBtnClickListener {

    protected RecyclerView mRecyclerView;
    protected static final int REQUEST_LOOKOVER_INFO = 100;
    protected SwipeRefreshLayout mSwipeRefresh;
    private boolean isRefresh;
    protected StateViewLayout mStateViewLayout;
    private int mScrollTotal;
    protected LayoutInflater mInflater;


    private K mAdapt;

    protected boolean mIsTop = true;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInflater = LayoutInflater.from(mActivity);
        EventBus.getDefault().register(this);
    }

    protected void initData() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mStateViewLayout == null) {
            mStateViewLayout = new StateViewLayout(getContext());
            mStateViewLayout.showLoadingView();
        } else {
            ViewGroup parent = (ViewGroup) mStateViewLayout.getParent();
            if (parent != null) {
                parent.removeView(mStateViewLayout);
            }
        }
        return mStateViewLayout;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        View listViewFragment = mInflater.inflate(R.layout.fragment_base_recycleview, null);
        mStateViewLayout.setSuccessView(listViewFragment);
        mStateViewLayout.setOnReloadClickListener(this);
        mRecyclerView = (RecyclerView) listViewFragment.findViewById(R.id.base_recycleview);
        mSwipeRefresh = (SwipeRefreshLayout) listViewFragment.findViewById(R.id.base_refresh);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new YuLeBaByLinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
        initRefresh();
        initScrollListener();
    }

    private void initScrollListener() {
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mScrollTotal += dy;
                if (mScrollTotal <= 0) {
                    mIsTop = true;
                } else {
                    mIsTop = false;
                }
            }
        });
    }


    //下拉刷新
    private void initRefresh() {
        mSwipeRefresh.setOnRefreshListener(this);
        mSwipeRefresh.setColorSchemeResources(R.color.swiperefresh_color1, R.color.swiperefresh_color2,
                R.color.swiperefresh_color3, R.color.swiperefresh_color4);
    }

    /**
     * 接受刷新信息的请求
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshEvent(RefreshEvent event) {
        if (event != null) {
            onRefresh();
        }
    }

    /**
     * 对TabIcon的点击处理 顶部就刷新  底部就是回到顶部
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTabSelectedEvent(TabSelectedEvent event) {
        if (mIsTop) {
//            onRefresh();
        } else {
            scrollToTop();
        }
    }

    private void scrollToTop() {
        mRecyclerView.smoothScrollToPosition(0);
    }

    @Override
    public void onRefresh() {
        mSwipeRefresh.setRefreshing(true);
        isRefresh = true;
        requestData();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    //请求数据
    public abstract void requestData();

    protected abstract K getRecycleAdapt(T result);

    protected HttpCallback callBack = new HttpCallback<T>() {
        @Override
        public void onSuccess(T result) {
            mAdapt = getRecycleAdapt(result);
            if (mAdapt != null) {
                mRecyclerView.setAdapter(mAdapt);
            }
            if (isRefresh) {
                refreshComplete();
                mAdapt.notifyDataSetChanged();
            } else {
                mStateViewLayout.showSuccessView();
            }
        }


        @Override
        public void onFail(String e) {
            if (isRefresh) {
                mSwipeRefresh.setRefreshing(false);
                isRefresh = false;
            } else {
                mStateViewLayout.showErrorView();
            }
            ToastUtil.showToast("服务器访问异常");
        }
    };

    protected boolean isRefreshing() {
        return isRefresh;
    }

    protected void refreshComplete() {
        mSwipeRefresh.setRefreshing(false);
        isRefresh = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    @Override
    public void onReloadBtnClick() {
        mStateViewLayout.showLoadingView();
        requestData();
    }
}
